﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using MyTcpIp.displacement;
using System.Threading;

namespace MyTcpIp
{
    public class WebCommunication
    {
        private string _dir="";
        public string dir { set { _dir = value; } get { return _dir; } }
        private static bool _flag = true;//true:文件写入完成，可以上传服务器；false:正在写入不能上传
        //public bool flag { set { _flag = value; } get { return _flag; } }
        public void StartUpload()
        {
            while(true)
            {
                DirectoryInfo root = new DirectoryInfo(_dir);
                foreach (FileInfo f in root.GetFiles())
                {
                    if(_flag)
                    {
                        bool ok = UploadFile(f.FullName);
                        if(ok)
                            File.Delete(f.FullName);
                    }
                    Thread.Sleep(1000);
                }
                Thread.Sleep(10);
            }
        }
        public void UploadFileBatch(string dir)
        {

        }
        public bool UploadFile(string filepath)
        {
            var uploadUrl = "http://127.0.0.1:8000/upload/";
            //var dic = new Dictionary<string, string>() {
            //        {"para1",1.ToString() },
            //        {"para2",2.ToString() },
            //        {"para3",3.ToString() },
            //    };
            //var postData = Utils.BuildQuery(dic);//转换成：para1=1&para2=2&para3=3
            var postData = "myname=BaoGangNo1";
            var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
            request.AllowAutoRedirect = true;
            request.Method = "POST";

            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //int pos = imgPath.LastIndexOf("\\");
            //string fileName = imgPath.Substring(pos + 1);

            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:txt\r\n\r\n", Path.GetFileNameWithoutExtension(filepath)));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            byte[] bdata = new byte[fs.Length];
            fs.Read(bdata, 0, bdata.Length);
            fs.Close();

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            //postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(bdata, 0, bdata.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            if (content == "ok")
                return true;
            return false;

        }
        /// <summary>
        /// 将振动位移数据存储为txt文件，每个通道一个文件
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="data"></param>
        public void data2file(string filepath, DisplacementData data)
        {
            _flag = false;
           //基础信息
            string boundary = "//---------------------------//";
            string t1 = data.Year.ToString() + data.Month.ToString("D2") + data.Day.ToString("D2") + data.Hour.ToString("D2") + data.Minute.ToString("D2") + data.Second.ToString("D2");
            string time = "Time:" + data.Year.ToString() + "年" + data.Month.ToString("D2") + "月" + data.Day.ToString("D2") + "日" + data.Hour.ToString("D2") + "时" + data.Minute.ToString("D2") + "分" + data.Second.ToString("D2") + "秒";

            //开始写入

            for (int i=0;i<data.CHDisData.Length;i++)
            {
                FileStream fs = new FileStream(filepath + "Displacement_Ch" + i.ToString("D2") + "_" + t1 + ".txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);

                sw.WriteLine(boundary);
                sw.WriteLine(time);
                CHDisplacementData ch = data.CHDisData[i];
                sw.WriteLine("ID, " + ch.ChID);
                sw.WriteLine("PK2PK, " + ch.PK2PK);
                sw.WriteLine("GapVoltage, " + ch.GapVoltage);
                sw.WriteLine("RoomSquareValue, "+ch.RoomSquareValue);
                sw.WriteLine("-----RawData----------");
                for(int j=0;j<ch.ZDs.Length;j++)
                {
                    sw.WriteLine(ch.ZDs[j]);
                }
                sw.Flush();
                sw.Close();
                fs.Close();
                //Thread.Sleep(100);
            }
            _flag = true;
        }
        public void deleteFileDir(string filepath)
        {
            //清空文件夹
            foreach (string d in Directory.GetFileSystemEntries(filepath))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
            }
        }
        public string uploadData(byte[] PicByte)
        {
            string contentType = "image/jpeg";
            //待请求参数数组
            //string fileName = @"C:\Users\jz\Desktop\zyj.jpg";
            //FileStream Pic = new FileStream(fileName, FileMode.Open);
            //PicByte = new byte[Pic.Length];
            ////将图片数据写入PicByre缓冲区中
            //Pic.Read(PicByte, 0, PicByte.Length);
            int lengthFile = PicByte.Length;
            Dictionary<string, string> dicPara = new Dictionary<string, string>();
            dicPara.Add("access_token", "1111");
            dicPara.Add("oauth_consumer_key", "2222");
            dicPara.Add("openid", "3333");
            dicPara.Add("content", "4444");
            //构造请求地址
            string strUrl = "http://127.0.0.1:8000/upload/";

            //设置HttpWebRequest基本信息
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
            //设置请求方式：get、post
            request.Method = "POST";
            //request.ContentType = contentType;
            //设置boundaryValue
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string boundary = "--" + boundaryValue;
            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundary;
            //设置KeepAlive
            request.KeepAlive = true;
            request.ProtocolVersion = HttpVersion.Version10;
            //设置请求数据，拼接成字符串
            StringBuilder sbHtml = new StringBuilder();
            foreach (KeyValuePair<string, string> key in dicPara)
            {
                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n" + key.Value + "\r\n\r\n");
            }
            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
            sbHtml.Append("PicBytes");
            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
            string postHeader = sbHtml.ToString();
            //将请求数据字符串类型根据编码格式转换成字节流
            Encoding code = Encoding.UTF8;
            byte[] postHeaderBytes = code.GetBytes(postHeader);
            byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "\r\n");
            //设置长度
            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
            request.ContentLength = length;

            //请求远程HTTP
            Stream requestStream = request.GetRequestStream();
            Stream myStream = null;
            try
            {
                //发送数据请求服务器
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(PicByte, 0, lengthFile);
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
                myStream = HttpWResp.GetResponseStream();
            }
            catch (WebException e)
            {
                //LogResult(e.Message);
                return "";
            }
            finally
            {
                //Pic.Close();
                //Pic.Dispose();
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }

            //读取处理结果
            StreamReader reader = new StreamReader(myStream, code);
            StringBuilder responseData = new StringBuilder();

            String line;
            while ((line = reader.ReadLine()) != null)
            {
                responseData.Append(line);
            }
            myStream.Close();
            return responseData.ToString();
        }
    }
}
